<link href="<?php echo URL::base() ?>media/vendor/css/ui-lightness/jquery-ui-1.10.4.custom.css" rel="stylesheet">
<script src="<?php echo URL::base() ?>media/vendor/js/jquery-1.7.1.min.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery.ui.core.min.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery.ui.widget.min.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery.ui.position.min.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery.ui.autocomplete.min.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery-1.7.1.min.js"></script>
<script src="<?php echo URL::base() ?>media/layer/layer.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery-ui-1.10.4.custom.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery-ui-timepicker-addon.min.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery-ui-timepicker-zh-CN.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery.ui.datepicker-zh-TW.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/Validform_v5.3.2_ncr_min.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/artdialog/jquery.artDialog.js"></script>
<style>
    #txtHint {
        position: absolute;
        top: 30px;
        left: 0;
        display: none;
        background-color: #EDFAF4;
        min-width: 281px;
        border: 1px solid #aaa;
        border-radius: 5px;
        height: 150px;
        overflow-x: hidden;
    }

    #txtHint li {
        list-style: none;
        color: #333;
        border: 1px solid #EDFAF4;
        padding: 0px 8px;
    }

    #txtHint li:hover {
        color: #c37100;
        background-color: #fdf8d5;
        border: 1px solid #fac900;
        border-radius: 25px;
    }

    #detail span:hover {
        color: #c37100;
    }

    #group {
        position: relative;
    }

    .table1 thead tr th, .table1 tbody tr td {
        text-align: center;
    }
</style>
<body id="pageContent" class="well">
<button class="btn btn-info" id="add_tr_btn" onclick="add()">+新增一行</button>
<div style="width: 100%;overflow-y: scroll;">
<table id="skus" class="table table1 table-hover table-striped table-condensed" style="margin-top: 10px;width: 1800px">
    <thead>
    <tr style="  background-color:#4EA392; color:#fff;">
        <th>SKU<span style="color: red">*</span></th>
        <th>供应商<span style="color: red">*</span></th>
        <th>仓库<span style="color: red">*</span></th>
        <th>主体</th>
        <th>单价</th>
        <th>数量<span style="color: red">*</span></th>
        <th>金额</th>
        <th>运费</th>
        <th>中文名</th>
        <th>付款方式<span style="color: red">*</span></th>
        <th>付款账号<span style="color: red">*</span></th>
        <th>联系人<span style="color: red">*</span></th>
        <th>报关品名</th>
        <th>商品编码</th>
        <th>单位</th>
        <th>储位</th>
        <th>交货日期</th>
        <th>计划员<span style="color: red">*</span></th>
        <th>跟单员</th>
        <th>状态</th>
        <th>操作</th>

    </tr>
    </thead>
    <tbody id="row">
    <tr>
        <td class="sku">
            <input style="width: 70px;" type="text" name="sku[]" value="" autocomplete="off" onfocus="do_autocomplete(this)">
        </td>
        <td class="supplier_id">
            <select class="" name="supplier_id[]" style="width: 150px;" onchange="change_supplier(this)" autocomplete="off">
                <option value="">请选择</option>
            </select>
        </td>
        <td class="warehouseid">
            <select class="" name="warehouseid[]" style="width: 90px;" onchange="checkEnterpriseDominant(this)" autocomplete="off">
                <option value="0">选择仓库</option>
                <?php foreach ($warehouses as $v){?>
                    <option value="<?php echo $v['id']; ?>"><?php echo $v['name']; ?></option>
                <?php }?>
            </select>
        </td>
        <td class="enterprise_dominant">
            <select class="" name="enterprise_dominant[]" style="width: 150px;" autocomplete="off">
                <option value="0">选择主体</option>
            </select>
        </td>        
        <td class="single_price"><input class="input-mini" name="single_price[]" value="" autocomplete="off" readonly ></td>
        <td class="quantity">
            <input class="input-mini" name="quantity[]" value="" style="width: 40px" autocomplete="off" onkeyup="clearNoNum(this)" onblur="count_money_in_count(this)">
        </td>
        <td class="money"> <input class="input-mini" name="money[]" value="" autocomplete="off" readonly></td>
        <td class="transportation_expense">
            <input class="input-mini" value="" name="transportation_expense[]" autocomplete="off" style="width: 40px" onkeyup="clearNoNum(this)">
        </td>
        <td class="sku_name"></td>
        <td class="pay_way_id">
            <select style="width: 80px;" name="pay_way_id[]">
                <option value="" >请选择</option>
            </select>
        </td>
        <td class="payaccountinfo_id">
            <select class="" name="payaccountinfo_id[]" style="width: 125px;">
                <option value="">请选择</option>
            </select>
            <div class="ratetype hidden">
                <select name="ratetype[]" style="width:70px;clear:left" onchange="rateTypeSelected(this)">
                    <option value="0">汇率类型</option>
                    <option value="10">卖出价</option>
                    <option value="20">中间价</option>
                    <option value="30">买入价</option>
                    <option value="40">自定义</option>
                </select>
                <input type="text" class="hidden" name="rate[]" style="width:30px;" />
            </div>
        </td>
        <td class="contact_id">
            <select class="" name="contact_id[]" style="width: 100px;">
                <option value="">请选择</option>
            </select>
        </td>
        <td class="item"></td>
        <td class="productNumber"></td>
        <td class="sku_unit"></td>
        <td class="storage_position"></td>
        <td class="arrive_date"><input style="width: 80px" name="arrive_date[]" class="datepicker" value="" autocomplete="off" ></td>
        <td class="create_user">
            <input type="hidden"  name="create_user[]" value="<?php echo $user->id?>" autocomplete="off"/>
            <input type="text"  name="purchaseplaner" value="<?php echo $user->nick?>" style="width: 50px;" onfocus="user_autocomplete(this)"/>
        </td>
        <td class="merchandiser"></td>
        <td class="status"></td>
        <td><button class="btn btn-info" onclick="delete_remove(this)">删除</button></td>
    </tr>
    </tbody>
    <tfoot class="hidden"><?php /* 请勿删除此行 */ ?></tfoot>
</table>
</div>
<div>
    <button id="tijiao" class="btn btn-info" style="margin-left:10px;">一键创建</button>
</div>
</body>
<?php 
echo '<script>var warehouses = ' . json_encode($warehouses) . ';</script>'; 
?>
<script type="text/javascript">
    $('table#skus>tbody#row>tr:eq(0)').clone().appendTo('table#skus>tfoot');
    /**
     * 设置时间控件
     */
    $.datepicker.setDefaults({ dateFormat: 'yy-mm-dd' });
    $(document).on('focus', ".datepicker", function (e) {
        $(this).datepicker({
            minDate: new Date(),
            dateFormat: 'yy-mm-dd'
        });
    });
    //新增
    function add() {
        $('tfoot tr').clone().appendTo('tbody#row');
    }
    //删除
    function delete_remove(obj) {
        $(obj).parent('td').parent('tr').remove();
    }
    /**
     * 自动提示sku信息
     */
    function do_autocomplete(obj) {
        if ( !$(obj).attr('readonly')
            && !$(obj).data("autocomplete")) {
            $(obj).autocomplete({
                autoFocus: true,
                minLength: 0,
                autoFill: true,
                source: '<?php echo URL::base(true)?>purchase/get_skuList',
                select: function (event, ui) {
                    /**
                     * 从建议列表中选中之后触发的事件
                     */
                    $(obj).val(ui.item.sku);
                    $(obj).attr("readonly", "readonly");
                    get_supplier(ui.item.sku, obj);
                    checkSkuDou();
                    return false;
                }
            });
        }
    }
    //自动提示计划员
    function user_autocomplete(obj) {
        $(obj).autocomplete({
            autoFocus: true,
            minLength: 0,
            autoFill: true,
            source: '<?php echo URL::base(true)?>purchase/get_users',
            select: function (event, ui) {
                /**
                 * 从建议列表中选中之后触发的事件
                 */
                $(obj).val(ui.item.name);
                $(obj).siblings('input[name=purchaseplaner_id]').val(ui.item.id);
                return false;
            }
        });
    }
    /**
     * 选中sku之后补全供应商信息
     */
    function get_supplier(sku, obj) {
        if (sku) {
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/getSupplierFromSku',
                    dataType: 'json',
                    data: {"sku": sku},
                    async: false,
                    success: function (re_data) {
                        if (re_data) {
                            var op = '';
                            for(var i=0;i<re_data.length;i++){
                                op += '<option value="'+re_data[i].supplier_id+'">'+re_data[i].supplier_name+'</option>'
                            }
                            $(obj).parent('td').siblings('.supplier_id').children('select').empty();
                            $(obj).parent('td').siblings('.supplier_id').children('select').append(op);

                            get_supplier_sku_info(re_data[0].supplier_id,sku,obj);
                            get_supplier_info(re_data[0].supplier_id,obj)

                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }
    //选中sku，供应商信息后补全信息
    function get_supplier_sku_info(supplier_id, sku, obj) {
        if (supplier_id && sku) {
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/getskuinfo',
                    dataType: 'json',
                    data: {"supplier_id": supplier_id, "sku": sku},
                    async: false,
                    success: function (re_data) {
                        if (re_data) {
                            show_supplier_sku_info(re_data,obj);
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }
    //选中仓库，补全储位信息
    function get_place_for_warehouseid(warehouseid, sku, obj) {
        if (warehouseid && sku) {
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/getPlaceForWarehouseId',
                    dataType: 'json',
                    data: {"warehouseid": warehouseid, "sku": sku},
                    async: false,
                    success: function (re_data) {
                        if (re_data) {
                            show_place_sku_info(re_data,obj);
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }
    function show_place_sku_info(re_data,obj){
        if (re_data) {
                $(obj).parent('td').siblings('.storage_position').text(re_data.place);//补全储位
        }
    }
    //自动补全供应商信息
    function get_supplier_info(supplier_id) {
        $.ajax({
            type: 'post',
            url: '<?php echo url::base(true)?>purchase/supplierpayway',
            dataType: 'json',
            data: {"supplier_id": supplier_id},
            async: false,
            success: function (re_data) {
                if (re_data) {
                    show_supplier_info(re_data);
                }
            },
            error: function () {
            }
        });
    }
    /**
     * 显示供应商的SKU信息，sku信息
     * 指定的行号
     */
    function show_supplier_sku_info(supplier_sku_info,obj) {
        if (supplier_sku_info) {
//            if (supplier_sku_info.sku) {
//                $(obj).val(supplier_sku_info.sku);
//            }
            if (supplier_sku_info.sku_name) {
                $(obj).parent('td').siblings('.sku_name').text(supplier_sku_info.sku_name);
//            $("#" + id).children().eq(1).text(supplier_sku_info.sku_name);
            }
            if (supplier_sku_info.declarationName) {
                $(obj).parent('td').siblings('.item').text(supplier_sku_info.declarationName);
            }
            if (supplier_sku_info.productNumber) {
                $(obj).parent('td').siblings('.productNumber').text(supplier_sku_info.productNumber);
            }
            if (supplier_sku_info.nuit) {
                $(obj).parent('td').siblings('.sku_unit').text(supplier_sku_info.nuit);
            }
            if (supplier_sku_info.place) {
                $(obj).parent('td').siblings('.storage_position').text(supplier_sku_info.place);
            }
            if (supplier_sku_info.price) {
                $(obj).parent('td').siblings('.single_price').children("input").val(supplier_sku_info.price);
            }
            if (supplier_sku_info.delivery) {
                $(obj).parent('td').siblings('.arrive_date').children("input").val(supplier_sku_info.delivery);
            }
            if (supplier_sku_info.merchandiser) {
                $(obj).parent('td').siblings('.merchandiser').text(supplier_sku_info.merchandiser);
            }
            if (supplier_sku_info.status) {
                $(obj).parent('td').siblings('.status').text(supplier_sku_info.status);
            }


        }
    }
    function change_supplier(obj) {
        var sku = $(obj).parent('td').siblings('.sku').children('input').val();
        var supplier_id = $(obj).val();
//        alert(supplier_id)
        get_supplier_sku_info(supplier_id,sku,obj);
        get_supplier_info(supplier_id,obj);
    }

    //获取供应商
    function get_supplier_info(supplier_id,obj) {
        $.ajax(
            {
                type: 'post',
                url: '<?php echo url::base(true)?>purchase/supplierpayway',
                dataType: 'json',
                data: {"supplier_id": supplier_id},
                async: false,
                success: function (re_data) {
                    if (re_data) {
                        show_supplier_info(re_data,obj);
                    }
                },
                error: function () {
                }
            }
        );
    }
    /**
     * 显示供应商详细信息
     * 联系人
     * 付款方式
     * 付款帐号
     */
    function show_supplier_info(supplier_info,obj) {
        var row = $(obj).parents('tr').first();
        if (supplier_info.supplier_contanct) {
            /**
             * 修改替换联系人选择框
             */
            $(row).find('select[name="contact_id[]"]').empty();
            $(row).find('select[name="contact_id[]"]').append(supplier_info.supplier_contanct);
        }

        if (supplier_info.supplier_payway) {
            /**
             * 修改替换付款方式选择框
             */
            $(row).find('select[name="pay_way_id[]"]').empty();
            $(row).find('select[name="pay_way_id[]"]').append(supplier_info.supplier_payway);
        }


        if (supplier_info.supplier_paybank) {
            /**
             * 修改替换付款帐号选择框
             */
            $(row).find('select[name="payaccountinfo_id[]"]').empty();
            $(row).find('select[name="payaccountinfo_id[]"]').append(supplier_info.supplier_paybank);
        }
        if(typeof(supplier_info.coinid) != 'undefined' && supplier_info.coinid != 1) {      // 外币账户
            $(row).find('div.ratetype').removeClass('hidden');
        } else {
            $(row).find('div.ratetype').addClass('hidden');
        }
    }
    function rateTypeSelected(obj) {
        if($(obj).val() == 40) {
            $(obj).next('input[name=\'rate[]\']').removeClass('hidden');
        } else {
            $(obj).next('input[name=\'rate[]\']').addClass('hidden');
        }
    }
    //校验数量
    function clearNoNum(obj) {
        obj.value = obj.value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
        obj.value = obj.value.replace(/^\./g, "");  //验证第一个字符是数字而不是.
        obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的.
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    }
    //输入数量后提示
    function count_money_in_count(obj) {
        if((/^(\+|-)?\d+$/.test(obj.value)) && obj.value>0){
            var td_single_price = $(obj).parents('tr').first().find('input[name="single_price[]"]').val();
            $(obj).parents('tr').first().find('input[name="money[]"]').val(td_single_price*obj.value);
        }else{
            layer.alert('请输入正确数量', {icon: 5});
        }
    }
    //限制主体
    function checkEnterpriseDominant(obj) {
        var row = $(obj).parents('tr').first();
        var ware_id = $(obj).find('option:selected').val();
        var enterprise_select = $(row).find('td.enterprise_dominant>select');
        var sku = $(row).find('td.sku>input').val();
        $(enterprise_select).find('option:not([value=0])').remove();
        if(typeof(warehouses[ware_id]) == 'object') {
            var warehouse = warehouses[ware_id];
            for(var i in warehouse.enterprise_dominant) {
                var enterprise = warehouse.enterprise_dominant[i];
                $('<option value="'+enterprise.id+'">'+enterprise.name+'</option>').appendTo(enterprise_select);
            }
        }

        get_place_for_warehouseid(ware_id,sku,obj);
    }
    //检查重复项
    function checkSkuDou(obj) {
        var skuArr = [];

        $("#row tr").each(function () {
            var temp = $(this).children(".sku").find("input").val();
            if (!temp) {
                return false;
            }
            skuArr.push(temp);
        });

        skuArr = skuArr.sort();

        for (var i = 0; i < skuArr.length; i++) {
            if (skuArr[i] === skuArr[i + 1]) {
                layer.alert('SKU有重复项请审核', {icon: 5});
                return false;
            }
        }
        return true;
    }
    //提交前检查
    function checkDouSku() {
        var skuArr = [];

        $("#row tr").each(function () {
            var temp = $(this).children(".sku").find("input").val();
            if (!temp) {
                layer.alert('SKU有空项', {icon: 5});
                return false;
            }
            skuArr.push(temp);
        });

        skuArr = skuArr.sort();

        for (var i = 0; i < skuArr.length; i++) {
            if (skuArr[i] === skuArr[i + 1]) {
                layer.alert('SKU有重复项请审核', {icon: 5});
                return false;
            }
        }

        return true;
    }
    $("#tijiao").click(function () {
        if (!checkDouSku()) return false;
        //if(!rateOrNot())return false;
        var sku_info = get_purchase_sku_info();
        if (sku_info!=false) {
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/createPurchaseAll',
                    dataType: 'json',
                    data: {"data": sku_info},
                    async: false,
                    success: function (re_data) {
                        if (re_data.code == 2) {
                            var tips = '创建成功';
                            layer.alert(tips, {icon: 6,closeBtn: 0},function () {
                                window.location.reload();
                            });
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    });
    /**
     * 获取采购单的SKU信息
     */
    function get_purchase_sku_info() {
        var sku_info_arr = [];
        $("#row").children('tr').each(function () {
            var sku_info = get_purchase_sku_info_row(this);
            if (sku_info) {
                sku_info_arr.push(sku_info);
            }else{
                return false;
            }
        });
        if (sku_info_arr) {
            return sku_info_arr;
        }
        else {
            layer.alert('请选择SKU', {icon: 5});
            return false;
        }
    }
    /**
     *  获取某一行的数据
     *
     */
    function get_purchase_sku_info_row(row) {
        var sku = $(row).find('input[name="sku[]"]').val().trim();
        if ($(row).find('input[name="sku[]"]').attr('readonly') && sku != '') {
            var quantity = $(row).find('input[name="quantity[]"]').val();
            var ware_id = $(row).find('select[name="warehouseid[]"] option:selected').val();
            var transportation_expense = $(row).find('input[name="transportation_expense[]"]').val();
            if(isNaN(quantity) || quantity <= 0){
                layer.alert('请输入'+sku+'的数量', {icon: 5});
                return false;
            }
            if(ware_id == 0){
                layer.alert('请选择'+sku+'仓库', {icon: 5});
                return false;
            }
            if(transportation_expense !='' && (!/\d+(\.{1}\d+)?$/.test(transportation_expense)|| transportation_expense<0) ){
                layer.alert('请输入正确运费', {icon: 5});
                return false;
            }
            if($(row).find('input[name="create_user[]"]').val() == ''){
                layer.alert('请输入计划员', {icon: 5});
                return false;
            }
            var fields = [
                'sku', 'supplier_id', 'warehouseid', 'enterprise_dominant', 'single_price', 'quantity', 'money', 'transportation_expense',
                'sku_name', 'pay_way_id', 'payaccountinfo_id', 'contact_id', 'item', 'productNumber', 'storage_position', 'arrive_date',
                'sku_unit', 'merchandiser', 'create_user', 'ratetype', 'rate'
            ];
            var sku_info = {};
            for(var i in fields) {
                var val = '';
                if($(row).find('select[name="'+fields[i]+'[]"]').size()) {
                    val = $(row).find('select[name="'+fields[i]+'[]"]>option:selected').val();
                } else if($(row).find('input[name="'+fields[i]+'[]"]').size()) {
                    val = $(row).find('input[name="'+fields[i]+'[]"]').val();
                } else if ($(row).find('td.'+fields[i]+" select").size() == 1) {
                    val = $(row).find('td.'+fields[i]+" select>option:selected").val();
                } else if ($(row).find('td.'+fields[i]+" input").size() == 1) {
                    val = $(row).find('td.'+fields[i]+" input").val();
                } else {
                    val = $(row).find('td.'+fields[i]+"").text();
                }
                sku_info[fields[i]] = val;
            }
            return sku_info;
        } else {
            return false;
        }
    }
</script>

